package cn.com.shuyangyang.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.com.shuyangyang.util.FileUploadUtil;
import cn.com.shuyangyang.util.ImgCut;

/**
 * 图片上传裁剪
 * 
 * @author shuyangyang
 * @E-Mail:shuyangyang@aliyun.com
 * @Bolg:http://www.shuyangyang.com.cn
 * @date 2017年3月8日 上午10:46:55
 */

@Controller
@RequestMapping("/UploadDemo")
public class UploadImgController {

	Logger logger = LoggerFactory.getLogger(UploadImgController.class);

	@RequestMapping(value = "/uploadHeadImage",method = RequestMethod.POST)
    public String uploadHeadImage(
            HttpServletRequest request,
            @RequestParam(value = "x") String x,
            @RequestParam(value = "y") String y,
            @RequestParam(value = "h") String h,
            @RequestParam(value = "w") String w,
            @RequestParam(value = "imgFile") MultipartFile imageFile
    ) throws Exception{
		String realPath = request.getSession().getServletContext().getRealPath("/");
		String resourcePath = "/Attachments/photo/";
		if (imageFile != null) {
			if (FileUploadUtil.allowUpload(imageFile.getContentType())) {
				String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());
				int end = fileName.lastIndexOf(".");
				String saveName = fileName.substring(0, end);
				File dir = new File(realPath + resourcePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File file = new File(dir, saveName + "_src.jpg");
				imageFile.transferTo(file);
				String srcImagePath = realPath + resourcePath + saveName;
				int imageX = Integer.parseInt(x);
				int imageY = Integer.parseInt(y);
				int imageH = Integer.parseInt(h);
				int imageW = Integer.parseInt(w);
				// 这里开始截取操作
				ImgCut.imgCut(srcImagePath, imageX, imageY, imageW, imageH);
				logger.debug("now {}", "上传成功之后的图片："+resourcePath + saveName + "_src.jpg");
				logger.debug("now {}", "上传成功裁剪之后的图片："+resourcePath + saveName + "_cut.jpg");
				request.getSession().setAttribute("imgSrc", resourcePath + saveName + "_src.jpg");// 成功之后显示用
				request.getSession().setAttribute("imgCut", resourcePath + saveName + "_cut.jpg");// 成功之后显示用
			}
		}
		return "redirect:/Web-Admin/Jcrop/success.jsp";
	}
}
